package com.vogue.flowmeter.api.retrofit;

import android.util.Log;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * 加密解密拦截器
 * 方案连接： https://back.waitalone.cn/mobilesecurity/okhttp.html
 * 方案连接： https://www.jianshu.com/p/c3c372ac1047
 */
public class DataEncryptInterceptor implements Interceptor {
    //服务器端公钥
    static String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobhGH4WMwMvJRUlTxWrCVIOQtsHijAxPJNvAWAgq80ADpFEWrpbcGB9cKqp6XHRH4k/CVtCUZ7jm9UKwhaeAm18sKtcwe+M8JFNX6FSHpgde0o8C9S/QpcmLxf4iN7nGZ7P3ZTvMdmKUcdRMsVQnsydG2Bj6gRxP2+kexEebTeODbdM7dHlkxAL0RxGWmX/ZOBzsoWZw2gKcC0vxwyIZBGHUdImG2T3nEA+VMfK2Yqv3uSYukmlKP+0mjfhrTtLFDuTV1VER9BfryBMvpQCxLO4pqgZnXPd+SOQcZHZ2OL0wqo5OX1+GPYx7TNxz5Qi76pK//T2mH7s6X/BuyT21HQIDAQAB";

    //客户端私钥
    static String PRIVATE_KEY = "MIICXAIBAAKBgQCMn5iUlddr2Mli61BUA+JDuxyahLyY5I/F8ui/HrTtViP0GYYKThn0VMrouDjVnMIlNklf3KCgubc80sEC5QXP/IRknTJw5gA9ekAIDP/muwpZvJcb7G+/AsWHtbeqN4HYUNj/Vv/FClUqSn9XufEnNx3WZWGoFi4jwQeKdPSlPwIDAQABAoGAB1T25qBdaAEYlvC/8nF1ZaSm3COZlbstB9wfaH+YXVuFal++TmE+FzAomDOquvB+auRGtRnSwi6MsD4o1BbO07JFgI1gpwbZDWiP9LBeM8R18is0lJ4xPLpfN7ZY0uMj0q6gp4KMb4lHwojWuRDE8anN8Y3J30uo3m0SYztMh4kCQQDeL9Crz9gVgIUSKJMddnMs+KwDC3fg3OJs44TkfCHGww/JNLp9yGGn86rUskyERvCUM5e/hKWWIVj9hbGg5sOFAkEAogYmfpfVnJLhapyR58Dhtj9VFWpjyAHSzOC7JuZ7VQv2uLBSGBPx5wqHuztoTDcHmxPysxeXLPOwBZmmDm828wJAd2hxF/UipyOj4Idn0Py4l2GpaBWAvptXILgB0p2XtW9di3/H/hNz0ERW+eo8zxYk8zDrC+Vo7E9NuSphtRxv1QJAMPNavfRxfRSDNgqHqlUD3GPV+NpjuxGR9oQPBvmrWU58A+CBbPTZqMvtpguUvzIBAkFMmf8OlW4qSAbbvJCtMQJBAKarMU+cWLX7XLPc0Bib7MiOMKU2DuhvA/xve8+mKbmKz+Tbci4UyS2HEfyYYecToe4PuFex3O/d3g+abYZffgY=";


    @Override
    public Response intercept(Chain chain) throws IOException {
        //请求
        Request request = chain.request();
        RequestBody oldRequestBody = request.body();
        Buffer requestBuffer = new Buffer();
        oldRequestBody.writeTo(requestBuffer);
        //待加密
        String oldBodyStr = requestBuffer.readUtf8();
        Log.e("DataEncryptInterceptor",oldBodyStr);
        requestBuffer.close();
        String newBodyStr = null;
        try {
            newBodyStr = onEncrypt(oldBodyStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody newBody = RequestBody.create(oldRequestBody.contentType(), newBodyStr);
        //构造新的request
        request = request.newBuilder()
                .header("Content-Type", newBody.contentType().toString())
                .header("Content-Length", String.valueOf(newBody.contentLength()))
                .method(request.method(), newBody)
                .build();
        //响应
        Response response = chain.proceed(request);
        if (response.code() == 200) {//只有约定的返回码才经过加密，才需要走解密的逻辑

            //用AES密钥解密oldResponseBodyStr
            ResponseBody oldResponseBody = response.body();
            //待解密
            String oldResponseBodyStr = oldResponseBody.string();
            Log.e("DataEncryptInterceptor",oldResponseBodyStr);
            String newResponseBodyStr = null;
            try {
                newResponseBodyStr = onDecrypt(oldResponseBodyStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            oldResponseBody.close();
            //构造新的response
            ResponseBody newResponseBody = ResponseBody.create(oldResponseBody.contentType(), newResponseBodyStr);
            response = response.newBuilder().body(newResponseBody).build();
        }
        response.close();
        //返回
        return response;
    }

    /**
     * 加密
     * @param value
     * @return
     * @throws Exception
     */
    private String onEncrypt(String value){
        String e= RSAUtils.encrypt(PUBLIC_KEY,value);
        Log.e("RSAUtils",e);
        return RSAUtils.encrypt(PUBLIC_KEY,value);
    }
    /**
     * 解密
     * @param value
     * @return
     * @throws Exception
     */
    private String onDecrypt(String value){
        String d= RSAUtils.decrypt(PRIVATE_KEY,value);
        Log.e("RSAUtils",d);
        return RSAUtils.decrypt(PRIVATE_KEY,value);
    }
}
